package com.wx.mall.sys.controller;


import com.wx.mall.common.api.CommonResult;
import com.wx.mall.common.exception.BusinessException;
import com.wx.mall.common.utils.DataResult;
import com.wx.mall.sys.entity.Role;
import com.wx.mall.sys.service.IRolePermissionService;
import com.wx.mall.sys.service.IRoleService;
import com.wx.mall.sys.vo.req.PageReqVO;
import com.wx.mall.sys.vo.req.RoleSetPermissionReqVO;
import com.wx.mall.sys.vo.req.RoleUpdateInsertReqVO;
import com.wx.mall.sys.vo.resp.PageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author j
 * @since 2020-03-18
 */
@RestController
@RequestMapping("/role")
@Api(tags = "角色模块相关接口")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IRolePermissionService iRolePermissionService;

    @GetMapping("/roles")
    @ApiOperation("查询所有角色")
    public CommonResult findAll() {
        List<Role> list = roleService.list();
        return CommonResult.success(list);
    }

    @PostMapping("/roles")
    @ApiOperation("分页查询接口")
    public DataResult findByPage(@Valid PageReqVO pageReqVO) {
        PageVO pageAll = roleService.findPageAll(pageReqVO);
        System.out.println(pageAll);
        return DataResult.success(pageAll);
    }

    @GetMapping("/role/{id}")
    @ApiOperation("根据id查询数据")
    public DataResult findById(@PathVariable("id") @NotNull Integer id) {
        Role byId = roleService.getById(id);
        return DataResult.success(byId);
    }

    @DeleteMapping("/role/{id}")
    @ApiOperation("删除接口")
    public DataResult deleteById(@PathVariable("id") @NotNull Integer id) {
        roleService.deleteById(id);
        return DataResult.success();
    }

    @PutMapping("/role")
    @ApiOperation("修改接口")
    public DataResult updateById(@Valid RoleUpdateInsertReqVO vo) {
        Role role = new Role();
        BeanUtils.copyProperties(vo, role);
        boolean b = roleService.updateById(role);
        if (!b) {
            throw new BusinessException(100001, "修改失败");
        }
        return DataResult.success();
    }

    @PostMapping("/role")
    @ApiOperation("新增接口")
    public DataResult add(@Valid RoleUpdateInsertReqVO vo) {
        Role role = new Role();
        BeanUtils.copyProperties(vo, role);
        boolean save = roleService.save(role);
        if (!save) {
            throw new BusinessException(100002, "新增失败");
        }
        return DataResult.success();
    }

    @PutMapping("/permission")
    @ApiOperation("设置权限接口")
    public DataResult setPermission(@Valid RoleSetPermissionReqVO vo) {
        roleService.setPermission(vo);
        return DataResult.success();
    }
}

